﻿using Mengsk.ProxyDelivery.App.Device;
using Mengsk.ProxyDelivery.App.Device.Kunhong;
using Mengsk.ProxyDelivery.App.UI;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Config
{
    /// <summary>
    /// DeviceConfigUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class WeightDeviceUserControl : UserControl, IPlugin
    {
        public string Title
        {
            get { return "称重设备"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public WeightDeviceUserControl()
        {
            InitializeComponent();
        }

        private void cbbDeviceTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IDevice device = this.cbbDeviceTypes.SelectedItem as IDevice;
            this.dpHostDeviceConfigs.Children.Clear();
            if (device != null)
            {
                IDeviceConfigUI ui = device.CreateNew();
                this.dpHostDeviceConfigs.Children.Add(ui.GetControl());
                this.dpHostDeviceConfigs.DataContext = ui;
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.cbbDeviceTypes.ItemsSource = new IDevice[] { new KunhongDevice() };
            string type = LocalConfigService.GetValue("WEIGHT_DEVICE", "");
            foreach (var item in this.cbbDeviceTypes.ItemsSource)
            {
                if (item.GetType().AssemblyQualifiedName == type)
                {
                    this.cbbDeviceTypes.SelectedItem = item;
                    break;
                }
            }
        }

        private void btnDeviceSave_Click(object sender, RoutedEventArgs e)
        {
            IDeviceConfigUI ui = this.dpHostDeviceConfigs.DataContext as IDeviceConfigUI;

            if (ui == null)
            {
                MessageBox.Show("请选择设备类型");
                return;
            }

            try
            {
                ui.Save();
                LocalConfigService.UpdateValue("WEIGHT_DEVICE", this.cbbDeviceTypes.SelectedItem.GetType().AssemblyQualifiedName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
